package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.entity.Provider;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.service.UserVoService;
import com.example.vo.BillVo;
import com.example.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private UserVoService userVoService;

	/**
	 * 员工登录
	 * @param request
	 * @param user
	 * @return
	 */
	@PostMapping("/login")
	public R<User> login(HttpServletRequest request, @RequestBody User user){

		//1、将页面提交的密码password进行md5加密处理
		String password = user.getPassword();

		//2、根据页面提交的用户名username查询数据库
		LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(User::getUsername,user.getUsername());
		User usr = userService.getOne(queryWrapper);

		//3、如果没有查询到则返回登录失败结果
		if(usr == null){
			return R.error("登录失败");
		}

		//4、密码比对，如果不一致则返回登录失败结果
		if(!usr.getPassword().equals(password)){
			return R.error("登录失败");
		}


		//6、登录成功，将员工id存入Session并返回登录成功结果
		request.getSession().setAttribute("user",usr.getId());
		return R.success(usr);
	}


	/**
	 * 员工退出
	 * @param request
	 * @return
	 */
	@PostMapping("/logout")
	public R<String> logout(HttpServletRequest request){
		//清理Session中保存的当前登录员工的id
		request.getSession().removeAttribute("user");
		return R.success("退出成功");
	}


	/**
	 * 信息分页查询
	 * @param page
	 * @param pageSize
	 * @param name
	 * @return
	 */
	@GetMapping("/page")
	public R<Page> page(int page, int pageSize, String name, String role){
		log.info("page = {},pageSize = {},name = {},Role = {}" ,page,pageSize,name,role);

		//构造分页构造器
		Page pageInfo = new Page(page,pageSize);

		//构造条件构造器
		LambdaQueryWrapper<UserVo> queryWrapper = new LambdaQueryWrapper();
		//添加过滤条件
		queryWrapper.like(StringUtils.isNotEmpty(name),UserVo::getUsername,name);
		queryWrapper.eq(StringUtils.isNotEmpty(role), UserVo::getRolename, role);

		//添加排序条件
		queryWrapper.orderByDesc(UserVo::getCreationdate);

		//执行查询
		userVoService.page(pageInfo,queryWrapper);

		return R.success(pageInfo);
	}


	/**
	 * 根据id查询员工信息
	 * @param id
	 * @return
	 */
	@GetMapping("/{id}")
	public R<User> getById(@PathVariable Long id){
		log.info("根据id查询用户信息...");
		User user = userService.getById(id);
		if(user != null){
			return R.success(user);
		}
		return R.error("没有查询到对应用户信息");
	}

	/**
	 * 根据id删除分类
	 * @param id
	 * @return
	 */
	@DeleteMapping
	public R<String> delete(Long id){
		log.info("删除用户，id为：{}",id);
		User user = userService.getById(id);
		boolean res = false;
		if(user != null && StringUtils.isNotBlank(user.getIdpicpath())) {
			String filePath = "E:\\img\\homework1\\" + user.getIdpicpath();
			File file = new File(filePath);
			if(file.exists()){
				res=file.delete();
			}
		}
		userService.removeById(id);
		if (res){
			log.info("用户附件已删除");
		}
		return R.success("用户信息删除成功");
	}

	@PostMapping
	public R<String> save(HttpServletRequest request, @RequestBody User user){

		log.info("新增用户，用户信息：{}",user.toString());


		//获得当前登录用户的id
		Long userId = (Long) request.getSession().getAttribute("user");

		user.setCreatedby(userId);
		user.setCreationdate(LocalDateTime.now());
		//设置初始密码123456，需要进行md5加密处理
		user.setPassword("123456");

		userService.save(user);

		return R.success("新增用户成功");
	}


	/**
	 * 根据id修改员工信息
	 * @param user
	 * @return
	 */
	@PutMapping
	public R<String> update(HttpServletRequest request,@RequestBody User user){

		log.info(user.toString());

		long id = Thread.currentThread().getId();
		log.info("线程id为：{}",id);
		Long userId = (Long) request.getSession().getAttribute("user");
		user.setModifyby(userId);
		user.setModifydate(LocalDateTime.now());
		userService.updateById(user);

		return R.success("用户信息修改成功");
	}


	@GetMapping("/all/rolename")
	public R<List<String>> getDistinctRolenames(){
		LambdaQueryWrapper<UserVo> queryWrapper = new LambdaQueryWrapper<>();

		//选择要查询的字段
		queryWrapper.select(UserVo::getRolename);

		//添加去重条件
		queryWrapper.groupBy(UserVo::getRolename);

		//执行查询
		List<Object> rolenamesObjs = userVoService.listObjs(queryWrapper);
		List<String> rolenames = new ArrayList<>();
		for (Object pronameObj : rolenamesObjs) {
			rolenames.add(String.valueOf(pronameObj));
		}

		return R.success(rolenames);
	}
}
